<template>
  <div class="rain rain-box">
    <title-group icon="icon-xiayusvg" title="各区域雨量" :right_txt="updateTime" :borderBotton="true"></title-group>
    <div class="map">
      <div id="main" class="main"></div>
      <div class="rain-map-text">{{ timeStr }}，超过50毫米的站点有{{ maxTotal }}个 。</div>
    </div>
  </div>
</template>

<script>

import { get7DaysWeatherData, getMinutelyWeather } from '@/api/getweatherData'
import features from './featuresData'
import areaData from './areaData'
import pieces from './pieces'
import { fetchData } from '@/api/apiList'
import dayjs from 'dayjs'
import * as echarts from "echarts";
//import series from '@/components/home/Map/series'

/**
 *  天地图返回的数据 
 * @param {Object} res  
 */
function get_upadate_time(res) {

  if (!res.result) {
    return '';
  }
  var list = res.result.daily.precipitation;
  for (let i of list) {
    if (i.date) {
      //返回字符串处理后的时间
      return i.date.split('T')[0] + ' ' + i.date.split('+')[1]
    }
  }
  return '';
}

function total_rainfall(name_str, list) {
  var valueList = [];
  list.map((item, index) => {
    if (item.region.indexOf(name_str) !== -1) {
      if (item?.rainfall) {
        item.rainfall.map((item2, index) => {
          valueList.push(item2.dayrainfall)
        });
      }
    }
  })
  valueList = valueList.reduce((total, item) => total + item) / valueList.length
  return valueList;
}

function totalLimiMax(list, max = 50) {
  var count = 0;
  list.map((item, index) => {
    if (item?.rainfall) {
      item.rainfall.map((item2, index) => {
        if (item2.dayrainfall >= max) {
          count++;
        }
      });
    }
  })
  return count;
}

export default {
  data() {
    return {
      geoJson: {
        type: "FeatureCollection",
        name: "440703",
        crs: {
          type: "name",
          properties: {
            name: "urn:ogc:def:crs:OGC:1.3:CRS84"
          }
        },
        features: features
      },
      chart: null,
      "data": areaData.data,
      "areaCoordinate": areaData.areaCoordinate,
      "updateTime":'更新时间'+dayjs().format('HH:mm'),
      listaa: []
    };
  },
  computed: {
    maxTotal() {
      return totalLimiMax(this.listaa, 50);
    },
    timeStr() {
      if (dayjs().format('H') >= 8) {
        return dayjs().format('MM月DD日08时至HH时');
      } else {
        return dayjs().subtract(1, 'day').format('MM月DD日08时至今08时');
      }

    }
  },
  methods: {
    echartsInit() {
      var myChart = echarts.init(document.getElementById("main"));
      this.chart = myChart
      function randomData() {
        return Math.round(Math.floor(Math.random() * 300));
      }
      echarts.registerMap("jm", this.geoJson);

      var option = {
        visualMap: {
          min: 0,
          max: 100,
          left: "20",
          top: "15",
          selectedMode: false,
          //   text: ["高", "低"], // 文本，默认为数值文本
          //   calculable: true,
          //   inRange: {
          //    color: ['#CCEEFF', '#99FFFF','#77DDFF', '#00BBFF', '#0066FF' ]
          //  },
          pieces: pieces,
        },
        series: [
          {
            type: "map",
            mapType: 'jm',
            zoom: 1.2,
            left: 90,
            right: 60,
            top: 40,
            bottom: 35,
            silent: true,
            select: {
              disabled: true,
            },
            label: {
              normal: {
                show: true
              },
              emphasis: {
                textStyle: {
                  color: "black"
                }
              }
            },
            itemStyle: {
              normal: {
                borderColor: "#389BB7",
                areaColor: "#black"
              },
              emphasis: {
                areaColor: "#EEFFBB",
                color: 'black',
                borderWidth: 2,
                borderColor: ''
              }
            },
            animation: false,
            data: this.data
            // animationDurationUpdate: 1000,
            // animationEasingUpdate: 'quinticInOut'
          }
        ]
      }
      myChart.setOption(option)
    },
    onWinResize() {
      this.chart.resize()
    },
    async getPrecipitation() {
      for (let key in this.areaCoordinate) {
        let { data: res } = await get7DaysWeatherData(this.areaCoordinate[key][0], this.areaCoordinate[key][1], 7);
        res = JSON.parse(res);

        /**
         * precipitation
         */
        // this.updateTime = JSON.parse(res).result.daily.precipitation[0].date.split('T')[0]+' '+JSON.parse(res).result.daily.precipitation[0].date.split('+')[1]
        this.updateTime = get_upadate_time(res);
        this.data.forEach(item => {
          item.name === key ? item.value = res.result.daily.precipitation[0].avg : ''
        })
      }
      console.log(this.data);
      this.echartsInit()
    }
  },
  async mounted() {
    this.echartsInit()
    window.addEventListener('resize', () => {
      console.log('555');
      this.onWinResize()
      location.reload()
    })
    //this.getPrecipitation()
  }
};
</script>

<style lang="less" scoped>
.rain-box {
    margin-top: 10px;
    background: white;
}
.rain {
  .right {
    right: 0;
  }

  .map {
    width: 100vw;

    // height: 25rem;
    .main {
      width: 100%;
      height: 100vw;
    }

    .text {
      padding: 5px;
      font-size: 16px;
      text-align: left;
      font-weight: 500;
      opacity: 0.8;
    }
  }
}
.rain-map-text {
    font-size: 1.2em;
    padding: 10px;
    border-top: 1px solid #e9e9e9;
    margin-top: 15px;
}
</style>